package com.tengxun.api.yuyin;

import com.tencentcloudapi.asr.v20190614.AsrClient;
import com.tencentcloudapi.asr.v20190614.models.SentenceRecognitionRequest;
import com.tencentcloudapi.asr.v20190614.models.SentenceRecognitionResponse;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;

@Slf4j
public class SentenceRecognitionExample {
    private static AsrClient client;
    
    static {
        try {
            // 初始化AsrClient
            Credential cred = new Credential("AKIDfDYfau0rXzDDyZ9czKivwleJkxzAFdtw", "vgFZfXBamkU2ZtzwsfO3bx5HMGUbYKsC");
            
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("asr.tencentcloudapi.com");
            
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            
            client = new AsrClient(cred, "ap-beijing", clientProfile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        try {
            // 方式1: 使用本地音频文件进行识别
            recognizeFromFile("C:\\Users\\11831\\Desktop\\启基永昌南京研发中心 2.m4a");
            
            // 方式2: 使用音频URL进行识别
            // recognizeFromUrl("http://example.com/audio.wav");
            
        } catch (TencentCloudSDKException e) {
            System.out.println("API调用错误: " + e.toString());
        } catch (IOException e) {
            System.out.println("文件读取错误: " + e.getMessage());
        }
    }
    
    /**
     * 使用本地音频文件进行语音识别
     * @param audioFilePath 音频文件路径
     */
    public static void recognizeFromFile(String audioFilePath) throws TencentCloudSDKException, IOException {
        // 将音频文件转换为Base64编码
        String base64AudioData = fileToBase64(audioFilePath);
        log.info("音频文件已转换为Base64编码base64AudioData: {}", base64AudioData);
        // 创建SentenceRecognition请求
        SentenceRecognitionRequest req = new SentenceRecognitionRequest();
        req.setProjectId(0L); // 项目ID，默认为0
        req.setSubServiceType(2L); // 子服务类型，2表示语音识别
        req.setEngSerViceType("16k_zh"); // 识别引擎类型，这里使用中文普通话16k
        req.setSourceType(1L); // 音频来源，1表示音频数据
        req.setVoiceFormat("m4a"); // 音频格式
        req.setUsrAudioKey("audio_" + System.currentTimeMillis()); // 用户音频唯一标识
        req.setData(base64AudioData); // Base64编码的音频数据
        req.setDataLen((long) base64AudioData.length()); // 音频数据长度
        
        // 调用SentenceRecognition接口
        SentenceRecognitionResponse resp = client.SentenceRecognition(req);
        
        // 处理响应结果
        System.out.println("=== 短音频识别结果 ===");
        System.out.println("请求ID: " + resp.getRequestId());
        System.out.println("识别结果: " + resp.getResult());
        System.out.println("时长: " + resp.getAudioDuration());
    }
    
    /**
     * 使用音频URL进行语音识别
     * @param audioUrl 音频文件URL
     */
    public static void recognizeFromUrl(String audioUrl) throws TencentCloudSDKException {
        // 创建SentenceRecognition请求
        SentenceRecognitionRequest req = new SentenceRecognitionRequest();
        req.setProjectId(0L); // 项目ID，默认为0
        req.setSubServiceType(2L); // 子服务类型，2表示语音识别
        req.setEngSerViceType("16k_zh"); // 识别引擎类型
        req.setSourceType(0L); // 音频来源，0表示音频URL
        req.setVoiceFormat("wav"); // 音频格式
        req.setUsrAudioKey("audio_" + System.currentTimeMillis()); // 用户音频唯一标识
        req.setUrl(audioUrl); // 音频URL
        
        // 调用SentenceRecognition接口
        SentenceRecognitionResponse resp = client.SentenceRecognition(req);
        
        // 处理响应结果
        System.out.println("=== 短音频识别结果 ===");
        System.out.println("请求ID: " + resp.getRequestId());
        System.out.println("识别结果: " + resp.getResult());
        System.out.println("时长: " + resp.getAudioDuration());
    }
    
    /**
     * 将本地文件转换为Base64编码字符串
     * @param filePath 文件路径
     * @return Base64编码字符串
     * @throws IOException 文件读取异常
     */
    public static String fileToBase64(String filePath) throws IOException {
        File file = new File(filePath);
        byte[] fileBytes = new byte[(int) file.length()];
        
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            fileInputStream.read(fileBytes);
        }
        
        return Base64.getEncoder().encodeToString(fileBytes);
    }
}
